package com.gmrz.uap.whitelist;

import com.gmrz.uap.cache.AmmsCacheUtil;
import com.gmrz.uap.cfg.SystemConst;
import com.gmrz.uap.common.ControllerSupport;
import com.gmrz.uap.model.WhiteList;
import com.gmrz.uap.operlog.OperLogService;
import com.gmrz.uap.resource.ResourceInterceptor;
import com.jfinal.aop.Before;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import redis.clients.jedis.exceptions.JedisConnectionException;

import java.util.ArrayList;
import java.util.List;

public class WhiteListController extends ControllerSupport {

    private static final Logger LOG = LogManager.getLogger(WhiteListController.class);

    private static final String _DEFAULT_ORDERBY_VISITADDRESS = "visit_address";

    /**
     * 白名单管理主页面
     */
    @Before(ResourceInterceptor.class)
    public void index() {
    }

    /**
     * 根据前台发过来的参数进行查询，可以进行分页，排序
     */
    public void list() {

        int page = getParaToInt(SystemConst.DATATABLE_PAGINATE_OFFSET, SystemConst.DATATABLE_PAGINATE_OFFSET_DEFAULT);
        int rows = getParaToInt(SystemConst.DATATABLE_PAGINATE_LIMIT, SystemConst.DATATABLE_PAGINATE_LIMIT_DEFAULT);

        String sort = getPara(SystemConst.DATATABLE_PAGINATE_SORT, _DEFAULT_ORDERBY_VISITADDRESS);
        String order = getPara(SystemConst.DATATABLE_PAGINATE_ORDER, SystemConst.DATATABLE_PAGINATE_ORDER_DEFAULT);

        WhiteList whiteList = getModel(WhiteList.class);

        LOG.info(whiteList.toString());

        Page<WhiteList> descPage = WhiteListService.me.findWhiteListListForPaginate(whiteList, page, rows, sort, order, getCookie(SystemConst.COOKIE_TENANT_ID));

        result.put(SystemConst.DATATABLE_PAGINATE_TOTAL, descPage.getTotalRow());
        result.put(SystemConst.DATATABLE_PAGINATE_ROWS, descPage.getList());

        render(responseJsonRender(result));
    }


    /**
     * 增加页面跳转
     */

    public void add() {
        render("form" + SystemConst.VIEW_EXTENDSION);
    }

    /**
     * 保存数据信息
     */
    public void save() {

        WhiteList whiteList = getModel(WhiteList.class);

        if (null == whiteList) {
            message = getRes().get("system.validator.paramnull");
            return;
        }
        whiteList.setTenantId(getCookie(SystemConst.COOKIE_TENANT_ID));
        whiteList.setVisitAddress(whiteList.getVisitAddress().trim());

        List<WhiteList> all = WhiteListService.me.findAll(whiteList.getTenantId());

        List<String> listnames = new ArrayList<String>();

        for (WhiteList w : all) {
            listnames.add(w.getVisitAddress());
        }

        if (!listnames.contains(whiteList.getVisitAddress())) {

            try {
                flag = WhiteListService.me.save(whiteList);

                if (flag) {
                    message = getRes().get("system.validator.add.success");
                    message = AmmsCacheUtil.deleteIfSuccess(AmmsCacheUtil.UAP_WHITELIST, message);
                } else {
                    message = getRes().get("system.validator.add.error");
                }
            } catch (JedisConnectionException jedisConnectionException) {
                message += getRes().get("redis.connection.failed");
                LOG.error(message, jedisConnectionException);
            }
        } else {
            message = getRes().get("system.validator.add.exist");
        }

        //增加系统操作日志
        OperLogService.me.addOperLog(getRes().get("resource.form.whitelist.add"), whiteList.getVisitAddress(), flag, message, getRequest());

        result.put(SystemConst.RESPONSE_RESULT_FLAG, flag);
        result.put(SystemConst.RESPONSE_RESULT_MESSAGE, message);
        render(responseJsonRender(result));
    }

    /**
     * 编辑页面跳转
     */
    public void edit() {
        WhiteList whiteList = WhiteList.dao.findById(getPara());
        setAttr("whiteList", whiteList);
        render("form" + SystemConst.VIEW_EXTENDSION);
    }

    /**
     * 修改数据信息
     */
    public void update() {
        WhiteList whiteList = getModel(WhiteList.class);

        if (null == whiteList) {
            message = getRes().get("system.validator.paramnull");
            return;
        }

        whiteList.setTenantId(getCookie(SystemConst.COOKIE_TENANT_ID));

        whiteList.setVisitAddress(whiteList.getVisitAddress().trim());

        WhiteList w = WhiteListService.me.getByVisitAdressAndAppids(whiteList.getVisitAddress(), getCookie(SystemConst.COOKIE_TENANT_ID));

        if (w == null) {

            try {
                flag = WhiteListService.me.update(whiteList);

                if (flag) {
                    message = getRes().get("system.validator.edit.success");
                    message = AmmsCacheUtil.deleteIfSuccess(AmmsCacheUtil.UAP_WHITELIST, message);
                } else {
                    message = getRes().get("system.validator.edit.error");
                }
            } catch (JedisConnectionException jedisConnectionException) {
                message += getRes().get("redis.connection.failed");
                LOG.error(message, jedisConnectionException);
            }

        } else {
            message = getRes().get("system.validator.add.exist");
        }

        //增加系统操作日志
        OperLogService.me.addOperLog(getRes().get("resource.form.whitelist.edit"), whiteList.getVisitAddress(), flag, message, getRequest());

        result.put(SystemConst.RESPONSE_RESULT_FLAG, flag);
        result.put(SystemConst.RESPONSE_RESULT_MESSAGE, message);
        render(responseJsonRender(result));
    }

    /**
     * 根据ID删除数据信息，可以同时删除多个，数据使用逗号(,)隔开
     */
    public void remove() {

        String ids = getPara(0);

        if (StrKit.isBlank(ids)) {
            message = getRes().get("system.validator.paramnull");
            render(responseJsonRender(result));
        }

        String wl_address = "";

        String[] idArr = ids.split(SystemConst._DEFAULT_SEPARATOR_COMMA);
        if (idArr.length >= 1) {
            for (String id : idArr) {
                WhiteList whiteList = WhiteListService.me.findOne(id);
                wl_address += whiteList.getVisitAddress();
            }
        }

        try {
            flag = WhiteListService.me.remove(ids);

            if (flag) {
                message = getRes().get("system.validator.remove.success");
                message = AmmsCacheUtil.deleteIfSuccess(AmmsCacheUtil.UAP_WHITELIST, message);
            } else {
                message = getRes().get("system.validator.remove.error");
            }
        } catch (JedisConnectionException jedisConnectionException) {
            message += getRes().get("redis.connection.failed");
            LOG.error(message, jedisConnectionException);
        }

        //增加系统操作日志
        OperLogService.me.addOperLog(getRes().get("resource.form.whitelist.remove"), wl_address, flag, message, getRequest());

        result.put(SystemConst.RESPONSE_RESULT_FLAG, flag);
        result.put(SystemConst.RESPONSE_RESULT_MESSAGE, message);
        render(responseJsonRender(result));
    }


    /**
     * 判断访问地址是否存在
     */
    public void exist() {
        flag = WhiteListService.me.exist(getPara("whiteList.visit_address"));
        render(responseJsonRender(flag));
    }

}
